<template>
  <Flex justify="center">
    <Upload
      :custom-request="customRequest"
      :accept="accept"
      :before-upload="onBeforeUpload"
    >
      <div class="upload-wrap">
        <p class="upload-wrap_icon text-center text-2xl">
          <CloudUploadOutlined
            :style="{ color: colorPrimary, fontSize: '80px' }"
          ></CloudUploadOutlined>
        </p>
        <p class="upload-wrap_description">
          <span>将文件拖到此处，或</span
          ><a :style="{ color: colorPrimary }">点击上传</a>
        </p>
      </div>
    </Upload>
  </Flex>
  <p class="py-5 text-center">
    <span>请上传格式为PNG\GPG的文件，文件大小建议小于20M</span>
  </p>
</template>

<script setup lang="tsx">
import { CloudUploadOutlined } from '@ant-design/icons-vue';
import {
  Flex,
  Modal,
  Upload,
  UploadProps,
  message,
  theme,
} from 'ant-design-vue';
import type { AxiosRequestConfig } from 'axios';

interface Props {
  uploadRequest: (data: FormData, config: AxiosRequestConfig) => Promise<any>;
}

const props = defineProps<Props>();
const accept = 'image/jpeg, image/png';

const emits = defineEmits<{
  success: [value: string];
}>();

const { defaultAlgorithm, defaultSeed } = theme;
const { colorPrimary } = defaultAlgorithm(defaultSeed);

const onBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isAccept = accept.includes(file.type!);
  if (!isAccept) {
    message.info(`请上传${accept}格式图片!`);
  }
  const isLtSize = file.size! / 1024 / 1024 < 500;
  if (!isLtSize) {
    message.info(`图片最大支持20MB!`);
  }
  return true;
};

const customRequest: UploadProps['customRequest'] = ({
  file,
  filename,
  onError,
  onSuccess,
  onProgress,
}) => {
  const formData = new FormData();
  formData.append(filename || 'file', file);
  props
    .uploadRequest(formData, {
      onUploadProgress: onProgress,
    })
    .then((res) => {
      onSuccess?.(res.data);
      emits('success', res.data);
    })
    .catch((err) => {
      Modal.error({
        title: '提示',
        content: err.message,
      });
      onError?.(err);
    });
};
</script>

<style lang="scss" scoped>
.upload-wrap {
  width: 384px;
  height: 192px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;
  border-radius: 4px;
  border: 1px solid #eee;

  &_icon {
    text-align: center;
    font-size: 24px;
  }
  &_description {
  }
}
</style>
